package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.context.BaseContext;
import org.example.mapper.ReportMapper;
import org.example.pojo.Category;
import org.example.pojo.Result;
import org.example.utils.PythonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@RestController

@Slf4j
public class ChatController {
    @Autowired
    private PythonUtils pythonUtils;

    @Autowired
    private ReportMapper reportMapper;

    @PostMapping("/ai/XunFei")
    public Result<String> askAI(@RequestBody String question) {
        log.info("访问讯飞的ai");
        String GetThings= pythonUtils.readPythonFile("0.py",question);
        if(GetThings==null){
            return Result.error("python报错");
        } else {
            return Result.success(GetThings);
        }

//        try {
//            ProcessBuilder pb = new ProcessBuilder("python", "src\\main\\resources\\python\\0.py", question);
//            pb.redirectErrorStream(true);
//            pb.environment().put("PYTHONIOENCODING", "utf-8"); //设置环境变量
//            Process p = pb.start();
//
//            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream(), "UTF-8")); //设置输入流的编码
//            StringBuilder output = new StringBuilder();
//
//            String line;
//            while ((line = reader.readLine()) != null) {
//                output.append(line);
//            }
//            reader.close();
//
//            int exitCode = p.waitFor();
//            if(exitCode==0) {
//                Long userId = BaseContext.getCurrentId();
//                log.info(String.valueOf(userId));
//                log.info(output.toString());
//                reportMapper.saveReport(output.toString(),userId);
//                return Result.success(output.toString());
//            } else {
//                System.out.println(output);
//                return Result.error("python报错");
//            }
//        } catch (Exception e) {
//            System.out.println("Python脚本执行失败: " + e.getMessage());
//            return Result.error("python脚本执行失败");
//        }
    }


    @GetMapping("/sleep/report")
    public Result<String> report(){
        Long userId = BaseContext.getCurrentId();
        log.info(String.valueOf(userId));
        String report = reportMapper.getReportByUserId(userId);
        if(report != null) {
            return Result.success(report);
        }
        return Result.error("暂无AI分析报告");
    }


    @PostMapping("/ai/sleep-question")
    public Result<Object> askSleepQuestion(@RequestBody String[] s) {
        StringBuilder analysisText = new StringBuilder("现在有一份周围入睡分贝大小数据：\n");
        float flag_db = 0;
        int flag_s = 0;
        List<String> volumeData = new ArrayList<>();
        for (int i = 0; i < s.length; i++) {
            if ((i+1) % 60 == 0) {
                volumeData.add(String.format("%d分钟:%.2fdB\n", (i+1) / 60, flag_db / 60));
                flag_db = 0;
                flag_s = 0;
            } else {
                flag_db += Float.parseFloat(s[i]);
                flag_s++;
            }
        }
        if (flag_db != 0) {
            volumeData.add(String.format("最后时段:%.2fdB\n", flag_db/flag_s));
        }
        log.info("{}",volumeData);
        analysisText.append(String.join(",",volumeData));
        askAI(analysisText + "请帮我分析睡眠情况，生成建议报告，包含数据分析、结论、睡眠环境音量建议报告、总体建议");//将分析文本发送给AI
        return Result.success();
    }
}
